<div>
    <fieldset>
        <legend>Изменить издание</legend>

        <span class="ErrorMessage" data-field="log" id="Log"></span>

        <div>Тип <?php echo $this->EditTypes()->ToHtml(); ?></div>
        <div><?php echo $this->FieldList()->ToHtml(); ?></div>

        <input type="hidden" value="<?php echo $this->data['edit_id']; ?>" id="edit_id" />
        <div style="margin-bottom: 1em;"><a href="AddField" id="DialogAddField">Добавить поле</a></div>

        <div class="PageMenu">
            <button id="AltEdit">Сохранить</button>
            <button id="DelEdit">Удалить</button>
        </div>
    </fieldset>

    <script type="text/javascript" id="AltEditScript">
        jsun.run(function() {

        jsun("#AltEdit").jsun.event({ onclick: AltEdit });
        jsun("#DialogAddField").jsun.event({ onclick: AddField });
        jsun("#DelEdit").jsun.event({ onclick: DelEdit });

        function LoadDict() {
            var f = jsun("#FieldSet").value.split(",");
            var i = this.getAttribute("data-i");

            var param = "u=Lib&m=Lib\\Dict/Select&field_id=" + f[i]
                + "&i=" + i;

            var dlg = new jsun.dialog({ title: "Словарь" });
            jsun.html.insert(dlg.content.v, jsun.html.sync_load(param));
            return dlg.show();
        }

        function ClearFile() {
            var cls = this.previousSibling,
                file = jsun("+input");
                file.setAttribute("type", "file");
                file.setAttribute("class", "FileInput");
                file.setAttribute("name", "File" + this.parentNode.parentNode.parentNode.getAttribute("data-i"));
                file.setAttribute("id", "File" + this.parentNode.parentNode.parentNode.getAttribute("data-i"));
            this.parentNode.replaceChild(file, cls);
            this.jsun.events.v = {};
            this.jsun.event({ onclick: LoadFile });
            this.setAttribute("value", "Загрузить");
        }

        function EditData() {
            var fid = jsun("#FieldSet"),
                field_num = fid.getAttribute("data-count"),
                fval = "", file = "";

            for(var i = 0; i < field_num; ++i) {
                var m = jsun("#F_" + i).value;
                fval += i > 0 ? "[^&]" + m : m;

                var f = jsun("#FileId_" + i);
                file += i > 0 ? "," + (f ? f.value : "") : (f ? f.value : "");
            }
            fval = encodeURIComponent(fval);
            fid = encodeURIComponent(fid.value);
            file = encodeURIComponent(file);

            return "&type_id=" + jsun("#type_id").value
                + "&fid=" + fid + "&fval=" + fval + "&file=" + file;
        }

        function EditDataObject() {

            var fid = jsun("#FieldSet"),
                field_num = fid.getAttribute("data-count"),
                fval = "", file = "";

            for(var i = 0; i < field_num; ++i) {
                var m = jsun("#F_" + i).value;
                fval += i > 0 ? "[^&]" + m : m;

                var f = jsun("#FileId_" + i);
                file += i > 0 ? "," + (f ? f.value : "") : (f ? f.value : "");
            }

            var data = {
                type_id: jsun("#type_id").value,
                fid: fid.value,
                fval: fval,
                file: file
            };
            return data;
        }

        function AddField() {

            var dlg = new jsun.dialog({ title: "Новое поле" });

            jsun.html.insert(dlg.content.v, jsun.html.sync_load("u=Lib&m=Lib\\Edition/FieldDialog"));
            return dlg.show();
        }

        function ChangeType() {

            var form = new jsun.form_request(),
                data = EditDataObject();

            data.u = 'Lib';
            data.p = 'Lib\\Edition/Add';

            form.submit({
                url: '?u=Lib&p=Lib\\Edition/Add',
                data: data
            });
        }

        function LoadFile() {
            var file = jsun("#File" + this.parentNode.parentNode.parentNode.getAttribute("data-i"));
            if (!file.value) return;

            var iframe = new jsun.frame_request(), _this = this;
            iframe.form.v.appendChild(file);
            iframe.submit({
                url: "?u=Dbase/Upload",
                data: [],
                enctype: "multipart/form-data",
                onload: function() {
                    var resp = iframe.window().Response;
                    if (resp.status != 0) {
                        jsun.dialog.warning('Ошибка', resp.err_msg).show();
                        _this.parentNode.insertBefore(iframe.form.v.firstChild, _this);
                    } else {
                        _this.parentNode.insertBefore(
                            jsun.dom.from_json({ text: resp.file }), _this
                        );
                        _this.nextSibling.setAttribute("value", resp.file_id);
                        _this.jsun.events.v = {};
                        _this.jsun.event({ onclick: ClearFile });
                        _this.setAttribute("value", "Отчистить");
                    }
                }
            });
        }


        function AltEdit() {

            var fid = jsun("#FieldSet"),
                field_num = fid.getAttribute("data-count"),
                fval = false;

            for(var i = 0; i < field_num; ++i) {
                if (jsun("#F_" + i).value.trim()) {
                    fval = true;
                    break;
                }
            }

            if (!fval) {
                jsun('#Log').innerHTML
                    = '<ul><li>Далжен быть указан хотя бы один текстовой атрибут</li></ul>';
            } else {
                jsun.json.load(function(p) {
                    if (p.STAT == 'OK') {
                        jsun.dialog.warning('Сообщение', 'Издание успешно изменено', function () {
                            //window.location.href = '?u=Lib&p=Lib\\Edition';
                            window.close();
                        }).show();
                    } else {
                        jsun.show_err(p);
                    }
                }, 'u=Edition/AltEdition&edit_id='
                    + jsun("#edit_id").value + EditData());
            }
        }

        function DelEdit() {

            jsun.json.load(function(p) {
                if (p.STAT == 'OK') {
                    jsun.dialog.warning('Сообщение', 'Издание удалено', function () {
                        window.close();
                    }).show();
                } else {
                    jsun.show_err(p);
                }
            }, "u=Edition/DelEdition&edit_id=" + jsun("#edit_id").value);
        }



        var count = jsun("#FieldSet").getAttribute("data-count");
        for(var i = 0; i < count; ++i) {
            jsun("#A_" + i).jsun.event({ onclick: LoadDict });
            var cls = jsun("#Load_" + i);
            if (cls) cls.jsun.event({ onclick: LoadFile });
        }

        jsun.swap.AddEdit = {};
        jsun.swap.AddEdit.LoadDict = LoadDict;
        jsun.swap.AddEdit.LoadFile = LoadFile;

        });
    </script>
</div>